package edu.ihs.lhpy.base;

import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.transaction.annotation.Transactional;

@Transactional //可以被继承，即对子类起作用
@SuppressWarnings("unchecked")
public abstract class BaseDaoImpl<T> implements BaseDao<T>{
	
	@Resource
	private SessionFactory sessionFactory;
	protected Class<T> clazz;//
	public BaseDaoImpl(){
		//通過反射得到T的真實類型
		ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();
		this.clazz = (Class) pt.getActualTypeArguments()[0];
		
	}

	@Override
	public void save(T entity) {
		getSession().save(entity);
	}

	@Override
	public void update(T entity) {
		getSession().update(entity);
	}
	
	@Override
	public void delete(Long id) {
		Object object = (T)getSession().get(clazz, id);
		getSession().delete(object);
	}
	@Override
	public T getById(Long id) {
		if(id == null){
			return null;
		}
		return (T)getSession().get(clazz, id);
	}

	@Override
	public List<T> getByIds(Long[] ids) {
		if(ids==null||ids.length==0){
			//空集合
			return Collections.EMPTY_LIST;
		}
		return getSession().createQuery(//
				" FROM "+clazz.getSimpleName()+" WHERE id IN ( :ids )")//
				.setParameterList("ids", ids)
				.list();
	}

	@Override
	public List<T> findAll() {
		return getSession().createQuery(//
				" FROM "+clazz.getSimpleName())//
				.list();
	}

	/**
	 * 获取当前可用的session
	 * @return
	 */
	protected Session getSession(){
		return sessionFactory.getCurrentSession();
	}
}
